﻿using System;
using System.ComponentModel;

namespace RG.Common.WPF.Dialogs
{
    [SupportDataBinding]
    public class BaseEditableObject<T> : IEditableObject, INotifyPropertyChanged, IFirePropertyChanged
    {
        protected T item;
        public T Item
        {
            get
            {
                OnBeforeItemGet();
                return item;
            }
            set
            {
                item = value.SerializeAndBack();
                OnItemChange();
                anotherBackup = item.ToWcfString();
            }
        }

        protected virtual void OnItemChange()
        {
        }

        protected virtual void OnBeforeItemGet()
        {
        }

        private string backup = "";

        private string anotherBackup = "";


        public bool IsItemChanged
        {
            get { return !anotherBackup.Equals(item.ToWcfString()); }
        }

        public void BeginEdit()
        {
            if (backup == "")
                backup = item.ToWcfString();
        }

        public void EndEdit()
        {
            backup = "";
        }

        public void CancelEdit()
        {
            if (backup == "") return;
            item = backup.FromWcfString<T>();
            backup = "";
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        public void OnPropertyChanged(string propertyName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
